<?php
/**
 * Контроллер заказов
 * 
 * Управление заказами
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления заказами
 *
 */
class ControllerOrder extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='order';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=1){
		parent::show();
		import('model.order');
		import('model.order');
		import('model.coupon');
		$shop_id = Vars::_(Router::SHOP_ID);
		$shop = Requestlocal::getString('shop',null);
		if($shop){
			$shop_id=$this->model('shop')->getId($shop);
		}
		$settings=array('where'=>ModelOrder::TABLE.DOT.ModelOrder::F_SHOP_ID.'='.$shop_id);
		if($page!==false){
			$settings['pagination']=array(
				'page'=>$page,
				'show'=>true
			);
		}
		$elements = $this->model()->load(
			false,
			array(
				ModelOrder::F_ORDER_ID,
				ModelOrder::F_CREATED,
				ModelOrder::F_DESCRIPTION,
				ModelOrder::F_STATUS,
				ModelOrder::F_STATUS_COMMENT,
				ModelOrder::F_USER_ID,
				ModelOrder::F_COUPON_ID,
				ModelUser::TABLE.DOT.ModelUser::F_NAME,
				ModelCoupon::TABLE.DOT.ModelCoupon::F_PERCENT
			),
			$settings
		);
		if(is_array($elements)){
			foreach ($elements as &$item) {
				$item['orderList'] = $this->model()->orderList($item[ModelOrder::F_ORDER_ID]);
			}
		}
		$this->view->set('list', $elements);
		$this->view->set('currency', $this->model('currency')->loadByShop($shop_id));
		
		$this->view->set('pagination',$this->model()->pagination);
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		import('model.order');
		import('model.coupon');

		$element = $this->model()->loadOne(
			$this->id,
			array(
				ModelOrder::F_ORDER_ID,
				ModelOrder::F_CREATED,
				ModelOrder::F_DESCRIPTION,
				ModelOrder::F_STATUS,
				ModelOrder::F_STATUS_COMMENT,
				ModelOrder::F_USER_ID,
				ModelOrder::F_SHOP_ID,
				ModelOrder::F_COUPON_ID,
				ModelUser::TABLE.DOT.ModelUser::F_NAME,
				ModelCoupon::TABLE.DOT.ModelCoupon::F_PERCENT
			)
		);
		$element['shop'] = $this->model('shop')->getName($element[ModelOrder::F_SHOP_ID]);
		$element['orderList'] = $this->model()->orderList($this->id);
		$this->view->set('element', $element);
		$this->view->set('currency', $this->model('currency')->loadByShop($element[ModelOrder::F_SHOP_ID]));
		
        $this->build();
	}
	/**
	 * Просмотр по конкретному магазину
	 * 
	 */
	public function showByShop(){
		parent::display(false);
		$view='info';
		$shop = Requestlocal::getString('shop',null);
		if($shop){
			$shop=$this->model('shop')->getId($shop);
		}
		if(!$shop && isset($_SESSION['shop_id'])) $shop = $_SESSION['shop_id'];
		if($shop){
			$this->showBySelector(ModelOrder::TABLE.DOT.ModelOrder::F_SHOP_ID.'="'.$shop.'"');
		} else {
			$this->order_info = false;
		}
		$this->view->set('info',$this->order_info);
		$this->build($view);
	}
	private function showBySelector($selector){
		import('model.category');
		$this->order_info=$this->model()->load(null,false,array(
			'fields' => array(ModelOrder::TABLE.DOT.'*', ModelCategory::TABLE.DOT.ModelCategory::F_TITLE.' AS category_name', '(SELECT COUNT(*) FROM comment WHERE comment.model_id = order.order_id AND comment.model="order") AS comments'),
			'where'=>$selector,
			'join'=>array(
				array('table'=>ModelCategory::TABLE, 'key'=>ModelCategory::F_CATEGORY_ID, 'join_table'=>ModelOrder::TABLE, 'join_field'=>ModelOrder::F_CATEGORY_ID)
		)
		));
		///надо чем то заменить
		foreach ($this->order_info as &$item) {
			$item['image'] = import('helper.image',true)->get($item[ModelOrder::F_IMAGE_ID]);
			$item['tags'] = $this->model()->getAllTags($item[ModelOrder::F_ORDER_ID]);
			$item['description'] = substr($item['description'],0,300);
		}
	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		parent::edit(true);
		Core::mustLogin();
		$this->view->set('element',$this->model()->loadOne($this->id,array(
		  ModelOrder::F_ORDER_ID,
		  ModelOrder::F_TITLE,
		  ModelOrder::F_DESCRIPTION,
		  ModelOrder::F_PRICE,
		  ModelOrder::F_PUBLISH,
		  ModelOrder::F_CATEGORY_ID
		  )));
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		Core::mustLogin();
		$this->build();
	}
	/**
	 * Создание
	 *
	 */
	public function create(){
		parent::save();
		if(!Core::mustLogin()) return false;
		$shop_id = $this->model('shop')->getId(Requestlocal::getString('s', ''));
		import('model.order');
		$result = false;
		$saveData=array(
			ModelOrder::F_SHOP_ID  		=> $shop_id,
        	ModelOrder::F_USER_ID  		=> Core::user(),
			ModelOrder::F_CREATED 		=> Core::date(),
        	ModelOrder::F_DESCRIPTION   => Requestlocal::getString('comment'),
        	ModelOrder::F_STATUS   		=> 1
		);

		if (!$result) {
			$result=$this->model()->save($saveData,$id);
		}
		if(is_numeric($result)){
            $id = $result;
        }
        if(!is_array($result)){
        	$orderList = Requestlocal::getVar("order",'post');
            if(is_array($orderList)){
	            $basket = array();
	            foreach ($orderList['basket'] as $item) {
	            	$basket[] = array(
	            		ModelProduct_to_order::F_PRODUCT_ID	=>$item['product_id'],
    					ModelProduct_to_order::F_ORDER_ID	=>$id,
    					ModelProduct_to_order::F_PRODUCT_COUNT=>$item['count']
	            	);
	            }
		    	$result=$this->model('product_to_order')->saveList($basket);
	        }
		}
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	$this->view->set('id',$id);
        	$this->view->result(false);
        }
	}
	/**
	 * Изменение
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
        $order_id = Requestlocal::getInt(ModelOrder::F_ORDER_ID,null,'post');
        $shop_id = $this->model('shop')->getId(Requestlocal::getString('shop', ''));
        if(!$shop_id) $shop_id = Vars::_(Router::SHOP_ID);
		$result=$this->model()->save(
			array(
            	ModelOrder::F_STATUS		=> Requestlocal::getInt(ModelOrder::F_STATUS),
				ModelOrder::F_STATUS_COMMENT=> Requestlocal::getString(ModelOrder::F_STATUS_COMMENT),
			),
			$order_id
		);
		if(is_numeric($result)){
            $order_id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		if(!Core::mustLogin()) return false;
		if(parent::delete(true)){
            $this->view->result();
            return true;
		}else{
            $this->view->result(true);
            return false;
        }
	}

	public function getShipMethods(){
		$this->view->set('info',array(
			array('name' => 'post', 'title' => 'Почта', 'description' => "Почтовая пересылка"),
			array('name' => 'novaPochta', 'title' => 'Новая Почта', 'description' => "Транспортная компания Новая Почта"),
			array('name' => 'autolux', 'title' => 'Автолюкс', 'description' => "Транспортная компания Автолюкс"),
			array('name' => 'UPS', 'title' => 'UPS', 'description' => "Международная транспортная компания UPS")
		));
		$this->build();
	}
	public function getPaymentMethods(){
		$this->view->set('info',array(
			array('name' => 'over', 'title' => 'Наложенный платеж', 'description' => "Вы платите при получении посылки в транспортной компании"),
			array('name' => 'card', 'title' => 'Кредитная карта', 'description' => "Вы платите оплачиваете кредитной картой сразу после оформлнея заказа"),
			array('name' => 'payPal', 'title' => 'PayPal', 'description' => "Вы платите через систему PayPal сразу после оформлнея заказа")
		));
		$this->build();
	}
}